package core;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.UnsupportedEncodingException;

/**
 * 这里默认手动禁止了“前置缓存”，需要的话请修改对应的请求方法。
 */
public class DataRequest<T extends Data> extends Request<DataResponse<T>> {

    protected final DataListener<T> listener;

    public DataRequest(String url, DataListener<T> listener) {
        this(Method.GET, url, listener);
    }

    public DataRequest(int method, String url, DataListener<T> listener) {
        super(method, url, listener);
        this.listener = listener;
        this.setShouldCache(false)
                .setRetryPolicy(DataRequester.getRetryPolicy());
    }

    @Override
    public String getBackupDomain() {
        return DataRequester.PRIVATE_DOMAIN;
    }

    protected DataResponse<T> prepareParseNetworkResponse(String parsed) {
        return null;
    }

    /**
     * 在返回最终结果之前，可以进行最后的处理
     */
    protected DataResponse<T> pruneNetworkResponse(DataResponse<T> response) {
        return response;
    }

    @Override
    protected Response<DataResponse<T>> parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        addMarker("parsed:" + parsed);
        parsed = ResponseUtil.pruneRespJsonr(parsed);
        DataResponse<T> dataResponse = prepareParseNetworkResponse(parsed);

        //检查结果
        if (dataResponse == null) {
            dataResponse = new DataResponse<>();
            ErrorMsgUtil.renderInnerErrorMsg(dataResponse);
        } else if (dataResponse.data == null) {
            ErrorMsgUtil.renderJSONParseErrorMsg(dataResponse);
        }

        return Response.success(pruneNetworkResponse(dataResponse), HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(DataResponse<T> response) {
        if (listener == null) { //没有响应处理器
            return;
        }
        if (ResponseUtil.isStatusAvailable(response.status)) {//响应码有效
            listener.onResponse(response.data);
        } else {
            listener.onDataErrorResponse(new DataError(response.status, response.errmsg));
        }
        listener.onDataFinished();
    }
}
